﻿using Czj_VoteSys.Models.Database;
using Czj_VoteSys.Models.Userlei;
using Czj_VoteSys.Service;
using Czj_VoteSys.Userlei;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Czj_VoteSys.Controllers
{
    [Route("api/[controller/[action]")]
    [ApiController]
    public class AuthenticationController : ControllerBase
    {
        private readonly IJWTService _jwtService;
        private readonly Czj_VoteSysContext _db;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="jwtService"></param>
        public AuthenticationController(IJWTService jwtService, Czj_VoteSysContext db)
        {
            _jwtService = jwtService;
            _db = db;
        }
        /// <summary>
        /// 创建token
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public string CreateToken(string email,string password)
        {
            return _jwtService.CreateToken(email,password);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public string UserInfo()
        {
            //获取用户信息
            return Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name).Value;
        }
        /// <summary>
        /// 注册 添加新用户
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string AddUser(SignRequest request)
        {
            //唯一的用户名
            //当数据库存在这个用户名时 做出响应
            //存在
            if (_db.Users.Any(x => x.Email == request.Email))
            {
                return "用户名已存在";
            }
            //获取到请求参数了

            //使用参数
            //添加新用户

            var user = new User
            {
                Email = request.Email,
                Password = request.Password,
                Password2 = request.Password2,
            };
            _db.Users.Add(user);
            var row = _db.SaveChanges();
            if (row > 0)
                return "注册成功";
            return "注册失败";
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public string LoginAccount(LoginRequest request)
        {
            //登录 逻辑

            //校验用户

            //1、先把用户查询出来

            var user = _db.Users.FirstOrDefault(x => x.Email == request.Email);
            if (user == null)
                return "用户不存在";

            //2、校验密码
            if (user.Password2 != request.Password)
                return "密码不正确";

            //都正确 确认是这个人
            return _jwtService.CreateToken(user.Email, user.Password);
        }
    }
}
